// API基础URL
const BASE_URL = 'http://localhost:3000'; // 根据实际情况修改

/**
 * 请求拦截器
 */
const requestInterceptor = (config) => {
	// 获取token
	const token = uni.getStorageSync('token');
	if (token) {
		config.header = {
			...config.header,
			'Authorization': `Bearer ${token}`
		};
	}
	
	// 添加基础URL
	if (config.url.indexOf('http') !== 0) {
		config.url = BASE_URL + config.url;
	}
	
	return config;
};

/**
 * 响应拦截器
 */
const responseInterceptor = (response) => {
	// 这里可以统一处理响应
	const { data } = response;
	
	// 处理token过期
	if (data.code === 401) {
		// 清除本地token
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
		
		// 跳转到登录页
		uni.showToast({
			title: '登录已过期，请重新登录',
			icon: 'none',
			duration: 2000,
			complete: () => {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}, 2000);
			}
		});
	}
	
	return response;
};

/**
 * 封装请求方法
 * @param {Object} options - 请求配置
 */
const request = (options = {}) => {
	// 应用请求拦截器
	options = requestInterceptor(options);
	
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				// 应用响应拦截器
				const response = responseInterceptor(res);
				resolve(response);
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

// 封装常用请求方法
const http = {
	baseURL: BASE_URL,
	get(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'GET',
			...options
		});
	},
	post(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'POST',
			...options
		});
	},
	put(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'PUT',
			...options
		});
	},
	delete(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'DELETE',
			...options
		});
	}
};

export default http; 